package udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private String serverIp;
    private int serverPort;
    // 网卡对象
    private DatagramSocket socket = null;

    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        this.socket = new DatagramSocket(); // 客户端段 不需要 绑定端口号 由操作系统自动分配端口号
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.print("-> ");
            String request = scanner.nextLine();
            if(request.equals("exit")) break;

            // 构造请求发送给服务器
            // DatagramPacket UDP协议中 传输数据的基本单位
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                                                InetAddress.getByName(serverIp),serverPort);
            socket.send(requestPacket);
            // 从服务器读取响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);// receive 方法 如果未接受到 数据 就会 阻塞
            String response = new String(responsePacket.getData(),0,requestPacket.getLength()).trim();
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        // 127.0.0.1 环回 ip 自己访问自己
        UdpEchoClient udpEchoClient = new UdpEchoClient("8.142.191.35",9090);
        udpEchoClient.start();
    }
}
